<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click='drawer=true;role={rid:0}'>添加角色</el-button>
        </el-col>
      </el-row>
      <!--角色列表-->
      <el-table :data="rolesList" border stripe>
        <el-table-column label="##" type="index"></el-table-column>
        <el-table-column label="角色" prop="name"></el-table-column>
        <el-table-column label="角色描述" prop="content"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click='drawer=true;role=scope.row'></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click='onDelete(scope.row)'></el-button>
            <el-tooltip class="item" effect="dark" content="权限分配" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"
                         @click="showSetRightDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--权限分配-->
    <el-dialog
      title="权限列表"
      :visible.sync="showSetRightDialogVisible"
      width="60%">
      <!--      树 控件-->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        check-strictly
        node-key="mid"
        default-expand-all
        :default-checked-keys="defKeys">
      </el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showSetRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights()">确 定</el-button>
  </span>
    </el-dialog>

<!--    添加角色 开始-->
    <el-drawer
      size='50%'
      :visible.sync='drawer'
      direction='rtl'>
      <el-row :gutter="20">
        <el-col :span="12" :offset="2">
          <h2 v-if='role.rid > 0'>角色修改</h2>
          <h2 v-else>角色添加</h2>
          <el-form  :model="role" label-width="80px">
            <el-form-item label="角色名称">
              <el-input v-model="role.name"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="role.content"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button v-if='role.rid > 0' type="primary" @click="onUpdata" >修改</el-button>
              <el-button v-else type="primary" @click="onSubmit">立即创建</el-button>
              <el-button @click="drawer=false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-drawer>
<!--    添加角色 结束-->
  </div>
</template>

<script>
  export default {
    data () {
      return {
        rolesList: [], // 角色
        rightsList: [], // 权限
        treeProps: {
          label: 'name',
          children: 'children'
        },
        defKeys: [], // 默认选中的节点
        roleid: 0,
        showSetRightDialogVisible: false, // 控制权限分配
        // 角色 添加/编辑
        drawer: false,
        role: {
          rid: 0
        }
      }
    },
    created () {
      this.getRolesList()
    },
    methods: {
      async getRolesList () {
        const { data: res } = await this.$http.get('Role/roles')
        if (res.code !== 1000) return this.$message.error(res.msg)
        this.rolesList = res.data
      },
      // 根据ID删除 对应的权限
      async removewRightById (role, rightId) {
        console.log(role, rightId)
        // 弹窗
        const confirmResult = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(msg => {
          return msg
        }).catch(err => {
          return err
        })

        if (confirmResult !== 'confirm') {
          return this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
        const { data: res } = await this.$http.post('Role/delNode', { rid: role.rid, mid: rightId })
        if (res.code !== 1000) {
          this.$message.error(res.msg)
        } else {
          this.$message.success(res.msg)
          this.getRolesList()
        }
      },
      // 展示分配权限
      async showSetRightDialog (row) {
        this.roleid = row.rid
        const { data: res } = await this.$http.get('Menu/menus2')
        if (res.code !== 1000) return this.$message.error(res.msg)
        this.rightsList = res.data
        this.defKeys = []
        if (row.role !== null) {
          this.defKeys = row.role.split(',')
        }
        this.showSetRightDialogVisible = true
      },
      // 递归获取权限ID
      getLeafKeys (node, arr) {
        if (!node.children) {
          return arr.push(node.mid)
        }
        node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      // 保存权限
      async allotRights () {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStrs = keys.join(',')
        const { data: res } = await this.$http.post('Role/editRole', { rid: this.roleid, role: idStrs })
        if (res.code !== 1000) return this.$message.error(res.msg)
        this.$message.success(res.msg)
        this.showSetRightDialogVisible = false
        this.getRolesList()
      },
      // 添加角色
      async onSubmit () {
        const { data: res } = await this.$http.post('Role/addrole', this.role)
        if (res.code !== 1000) return this.$message.error(res.msg)
        this.$message.success('保存成功')
        this.drawer = false
        this.getRolesList()
      },
      // 更新角色
      async onUpdata () {
        const { data: res } = await this.$http.post('Role/uprole', this.role)
        if (res.code !== 1000) return this.$message.error(res.msg)
        this.$message.success('保存成功')
        this.drawer = false
        this.getRolesList()
      },
      // 删除角色
      async onDelete (data) {
        const confirmResult = await this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(msg => {
          return msg
        }).catch(err => {
          return err
        })

        if (confirmResult !== 'confirm') {
          return this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
        const { data: res } = await this.$http.post('Role/delRole', data)
        if (res.code !== 1000) return this.$message.error(res.msg)
        this.$message.success('删除成功')
        this.drawer = false
        this.getRolesList()
      },
      // 选中父节点
      checkeTree (data) {
        let thisNode = this.$refs.treeRef.getNode(data.mid) // 获取当前节点
        const keys = this.$refs.treeRef.getCheckedKeys() // 获取已勾选节点的key值
        console.log(thisNode)
        console.log(keys)
        if (thisNode.checked) { // 当前节点若被选中
          for (let i = thisNode.level; i > 1; i--) { // 判断是否有父级节点
            if (!thisNode.parent.checked) { // 父级节点未被选中，则将父节点替换成当前节点，往上继续查询，并将此节点key存入keys数组
              thisNode = thisNode.parent
              keys.push(thisNode.data.mid)
            }
          }
        }
        if (thisNode.checked === false) {
          // alert(1)
        }
        this.$refs.treeRef.setCheckedKeys(keys) // 将所有keys数组的节点全选中
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-table {
    margin: 12px;
    font-size: 12px;
  }
  .el-tag {
    margin: 7px;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }
</style>
